package cn.jly.servlet3;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lanyangji
 * @description 测试servlet3.0异步请求
 * @date 2020/11/16 上午 8:26
 */
@WebServlet(value = "/hello", asyncSupported = true)
public class HelloAsyncServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(Thread.currentThread() + " 主线程 start ..");

        // 1. 支持异步处理 asyncSupported=true
        // 2. 开启异步模式
        final AsyncContext asyncContext = req.startAsync();
        // 3. 进行异步处理
        asyncContext.start(() -> {
            try {
                // 模拟耗时业务
                sayHello();

                // 4. 获取响应
                final ServletResponse response = asyncContext.getResponse();
                response.getWriter().write("hello async..");

                asyncContext.complete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        System.out.println(Thread.currentThread() + " 主线程 end ..");
    }

    private void sayHello() throws InterruptedException {
        System.out.println(Thread.currentThread() + " 辅线程 processing");
        Thread.sleep(3000);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
